<template>
  <div class="goods-image">
    <div class="large" v-show="!isOutside" :style="{backgroundImage:`url(${images[currIndex]})`,...bgPosition}"></div>
    <div class="middle"  ref="target">
      <img :src="images[currIndex]" alt="">
      <div class="layer" v-show="!isOutside" :style="layerStyle"></div>
    </div>
    <ul class="small">
      <li v-for="(img,i) in images" :key="img" :class="{active:i===currIndex}">
        <img @mouseenter="currIndex=i" :src="img" alt="">
      </li>
    </ul>
  </div>
</template>
<script>
import { useMouseInElement } from '@vueuse/core'
import { ref, watch, reactive } from 'vue'
export default {
  name: 'GoodsImage',
  props: {
    images: {
      type: Array,
      default: () => []
    }
  },
  setup () {
    const currIndex = ref(0)
    const target = ref(null)
    // 以哪个元素为基准计算鼠标的位置
    const { elementX, elementY, isOutside } = useMouseInElement(target)
    const layerStyle = reactive({ top: '0px', left: '0px' })
    // 定义放大指定的位置
    const bgPosition = reactive({
      'background-position-x': '0px',
      'background-position-y': '0px'
    })
    watch([
      elementX,
      elementY,
      isOutside
    ], () => {
      // top，left 用来确定绝对定位下，遮罩元素的位置
      let top = elementY.value - 100
      let left = elementX.value - 100
      // 遮罩不能出图片区域
      if (top > 200) top = 200
      if (left > 200) left = 200
      if (top < 0) top = 0
      if (left < 0) left = 0
      // 给遮罩元素赋值位置
      layerStyle.top = top + 'px'
      layerStyle.left = left + 'px'

      bgPosition['background-position-x'] = (-2 * left) + 'px'
      bgPosition['background-position-y'] = (-2 * top) + 'px'
    })
    return { currIndex, elementX, elementY, isOutside, target, layerStyle, bgPosition }
  }
}
</script>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
   position: relative;
   cursor: move;
    display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
   .layer {
     width: 200px;
     height: 200px;
     background: rgba(0,0,0,.2);
     left: 0;
     top: 0;
     position: absolute;
   }

  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
  }
  .small {
    width: 80px;
    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;
      &:hover,&.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>
